/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lhwalq.books.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.lhwalq.books.R;
import com.lhwalq.books.base.Constant;
import com.lhwalq.books.bean.Recommend;
import com.lhwalq.books.manager.CollectionsManager;
import com.lhwalq.books.utils.FileUtils;
import com.lhwalq.books.utils.PermissionHelper;
import com.lhwalq.books.utils.SharedPreferencesUtil;
import com.umeng.analytics.MobclickAgent;

import net.youmi.android.normal.spot.SplashViewSettings;
import net.youmi.android.normal.spot.SpotListener;
import net.youmi.android.normal.spot.SpotManager;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SplashActivity extends AppCompatActivity {

    @Bind(R.id.rl_splash)
    RelativeLayout splashLayout;

    private PermissionHelper mPermissionHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 移除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(com.lhwalq.books.R.layout.activity_splash);
        ButterKnife.bind(this);

        // 当系统为6.0以上时，需要申请权限
        mPermissionHelper = new PermissionHelper(this);
        mPermissionHelper.setOnApplyPermissionListener(new PermissionHelper.OnApplyPermissionListener() {
            @Override
            public void onAfterApplyAllPermission() {
                setupSplashAd();
            }
        });
        if (Build.VERSION.SDK_INT < 23) {
            // 如果系统版本低于23，直接跑应用的逻辑
            setupSplashAd();
        } else {
            // 如果权限全部申请了，那就直接跑应用逻辑
            if (mPermissionHelper.isAllRequestedPermissionGranted()) {
                setupSplashAd();
            } else {
                // 如果还有权限为申请，而且系统版本大于23，执行申请权限逻辑
                mPermissionHelper.applyPermissions();
            }
        }
    }

    private void initBooks() {
//        addBook("三国演义", "sanguo.txt", "1.2M", R.drawable.sanguo);
//        addBook("水浒传", "shuihu.txt", "1.7M", R.drawable.shuihu);
//        addBook("西游记", "xiyou.txt", "1.3M", R.drawable.xiyouji);
//        addBook("红楼梦", "honglou.txt", "1.3M", R.drawable.honglou);

//        addBook("庶女有毒(锦绣未央)", "shunvyoudu.txt", "5.7M", R.drawable.shunvyoudu);
//        addBook("琅琊榜", "langyabang.txt", "1.6M", R.drawable.huge);

        addBook("哈利波特与魔法师", "1.txt", "327K", R.drawable.h1);
        addBook("哈利波特与密室", "2.txt", "354K", R.drawable.h2);
        addBook("哈利波特与阿兹卡班的囚徒", "3.txt", "446K", R.drawable.h3);
        addBook("哈利波特与火焰杯", "4.txt", "800K", R.drawable.h4);
        addBook("哈利波特与凤凰社", "5.txt", "1M", R.drawable.h5);
        addBook("哈利波特与混血王子", "6.txt", "548K", R.drawable.h6);
        addBook("哈利波特与死亡圣器", "7.txt", "778K", R.drawable.h7);
    }

    private void addBook(String bookTitle, String bookPath, String bookSize, int bookPathId) {
        // 拷贝到缓存目录
        Recommend.RecommendBooks books = new Recommend.RecommendBooks();
        books._id = bookTitle;
        books.path = bookPath;
        books.title = bookTitle;
        books.isFromSD = true;
        books.lastChapter = bookSize;
        books.bookPath = bookPathId;
        FileUtils.createFile(new File(FileUtils.getChapterPath(books._id, 1)));
        FileUtils.copyData(books.path, FileUtils.getChapterPath(books._id, 1));
        // 加入书架
        CollectionsManager.getInstance().add(books);
    }

    /**
     * 设置开屏广告
     */
    private void setupSplashAd() {
        if (SharedPreferencesUtil.getInstance().getBoolean(Constant.IS_FIRST_OPEN_APP, true)) {
            initBooks();
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            // 创建开屏容器
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.ABOVE, R.id.view_divider);

            // 对开屏进行设置
            SplashViewSettings splashViewSettings = new SplashViewSettings();
            // 设置跳转的窗口类
            splashViewSettings.setTargetClass(MainActivity.class);
            // 设置开屏的容器
            splashViewSettings.setSplashViewContainer(splashLayout);

            // 展示开屏广告
            SpotManager.getInstance(this)
                    .showSplash(this, splashViewSettings, new SpotListener() {

                        @Override
                        public void onShowSuccess() {
                            splashLayout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onShowFailed(int errorCode) {
                        }

                        @Override
                        public void onSpotClosed() {
                        }

                        @Override
                        public void onSpotClicked(boolean isWebPage) {
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        setupSplashAd();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPermissionHelper.onActivityResult(requestCode, resultCode, data);
    }

}
